package com.jiraonthego;


import javax.net.ssl.HostnameVerifier;

import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.jiraonthego.proxy.HTTPTask;

public class MainActivity extends Activity implements OnClickListener, IActivityHandler {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

		DefaultHttpClient client = new DefaultHttpClient();
		SchemeRegistry registry = new SchemeRegistry();
		SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
		socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
		registry.register(new Scheme("https", socketFactory, 443));
		SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
		//DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
		//HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
		setContentView(R.layout.login_view);
		
		Button btnLogin = (Button)findViewById(R.id.button1);
		btnLogin.setOnClickListener(this);
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public void resultHandler(JSONObject result) {
		Intent intent = new Intent(this, IssuesListActivity.class);
		//intent.putExtra("issues", result);
		JSONObject[] arrIssues;
		try {
			JSONArray jsonArray = result.getJSONArray("issues");
		    for (int i = 0; i < jsonArray.length(); i++) {
		        JSONObject explrObject = jsonArray.getJSONObject(i);
		    }
		}
		catch(JSONException e) {
			e.printStackTrace();
		}
		startActivity(intent);
	}
	
	public void onClick(View v) {
		HTTPTask task = new HTTPTask();
		String userDetails = "Basic " + Base64.encodeToString(new String("jiratesting08:bangalore08").getBytes(), 1);
		//String url = "https://jiraonthego.atlassian.net/rest/api/2/issue/createmeta";
		String url = "https://jiraonthego.atlassian.net/rest/api/2/search?jql=assignee=jiratesting08&resolution=Unresolved&expand=id,key";
		task.execute(this, url, userDetails);
	}

}
